
package Filter;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.helpers.XMLReaderFactory;


public class Main {

    public static void main(String[] args) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            parser.parse(new File("cd_catalog.xml"), new ShipOrderHandler());

            ShipOrderTitleFilter filter = new ShipOrderTitleFilter();
            XMLReader reader = XMLReaderFactory.createXMLReader();

            filter.setParent(reader);
            filter.setContentHandler(new ShipOrderHandler());
            filter.parse(new InputSource(new FileInputStream("cd_catalog.xml")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//Ham FIlter
    class ShipOrderTitleFilter extends XMLFilterImpl{
        private boolean itemFound = true;

        @Override
        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
            if(qName.equals("title")){
                itemFound = true;
                //???
                super.startElement(uri, localName, qName, atts);
            }
        }
    }

    //Ham Shndler
    class ShipOrderHandler extends DefaultHandler{
        private boolean itemFound = false;

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if(qName.equals("title")){
                itemFound = true;
            }
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if(itemFound){
                System.out.println(new String(ch, start, length));
                itemFound = false;
            }
        }
    }
